package com.wsoft.im.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wsoft.core.service.CommonMemberService;
import com.wsoft.core.utils.LoginUserUtil;
import com.wsoft.core.vo.MemberVO;
import com.wsoft.im.entity.ImMemberConfigEntity;
import com.wsoft.im.enums.MemberConfigEnum;
import com.wsoft.im.manager.ImMemberConfigManager;
import com.wsoft.im.mapper.ImMemberConfigMapper;
import com.wsoft.im.query.member.config.MemberConfigQuery;
import com.wsoft.im.query.member.config.MemberListQuery;
import com.wsoft.im.query.member.config.WhiteConfigQuery;
import com.wsoft.im.service.IImMemberConfigService;
import com.wsoft.im.vo.MemberConfigVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Z001
 * @since 2025年01月14日 09:21:32
 */
@Service
public class ImMemberConfigServiceImpl extends ServiceImpl<ImMemberConfigMapper, ImMemberConfigEntity> implements IImMemberConfigService {

    @Resource
    private ImMemberConfigManager memberConfigManager;
    @Resource
    private CommonMemberService memberService;

    /**
     * 管理员添加白名单成员
     * @param query
     * @return
     */
    @Override
    public boolean addWhiteList(WhiteConfigQuery query) {
        //获取白成员名单列表,防止重复配置
        List<ImMemberConfigEntity> list = memberConfigManager.getWhiteMemberConfigList();
        List<Long> collect = list.stream().map(ImMemberConfigEntity::getMemberId).collect(Collectors.toList());
        List<Long> memberIdList = query.getMemberIdList();
        memberIdList = memberIdList.stream().filter(item-> !collect.contains(item)).collect(Collectors.toList());
        return memberConfigManager.addWhiteList(memberIdList);
    }

    /**
     * 移除白名单列表
     * @param query
     * @return
     */
    @Override
    public boolean removeWhiteList(WhiteConfigQuery query) {
        return memberConfigManager.removeWhiteList(query.getMemberIdList());
    }

    /**
     * 添加白名单/黑名单
     * @param query
     * @return
     */
    @Override
    public boolean addConfigList(MemberConfigQuery query) {
        Long memberId = query.getMemberId();
        Long curMemberId = LoginUserUtil.getUserInfo().getLoginUserVO().getId();
        ImMemberConfigEntity memberConfig =memberConfigManager.getByMemberId(curMemberId);
        //不存在用户配置信息,默认为黑名单
        if(ObjUtil.isEmpty(memberConfig)){
            memberConfig = new ImMemberConfigEntity();
            memberConfig.setMemberId(curMemberId);
            memberConfig.setFilterType(MemberConfigEnum.BLACK.getType());
            memberConfig.setBlackList(memberId.toString());
        }else{
            if(MemberConfigEnum.WHITE.getType().equals(memberConfig.getFilterType())){
                //白名单
                if(StrUtil.isBlank(memberConfig.getWhiteList())){
                    memberConfig.setWhiteList(memberId.toString());
                }else{
                    memberConfig.setWhiteList(addOrRemoveValue(memberConfig.getWhiteList(),null, memberId.toString()));
                }
            }else{
                //黑名单
                if(StrUtil.isBlank(memberConfig.getBlackList())){
                    memberConfig.setBlackList(memberId.toString());
                }else{
                    memberConfig.setBlackList(addOrRemoveValue(memberConfig.getBlackList(),null, memberId.toString()));

                }
            }
        }
        return  memberConfigManager.addWhiteBlackMember(memberConfig,curMemberId);
    }

    /**
     * 移除白名单/黑名单
     * @param query
     * @return
     */
    @Override
    public boolean removeConfigList(MemberConfigQuery query) {
        Long memberId = query.getMemberId();
        Long curMemberId = LoginUserUtil.getUserInfo().getLoginUserVO().getId();
        ImMemberConfigEntity memberConfig =memberConfigManager.getByMemberId(curMemberId);
        //不存在用户配置信息,默认为黑名单
        if(ObjUtil.isEmpty(memberConfig)){
            return false;
        }
        if(MemberConfigEnum.WHITE.getType().equals(memberConfig.getFilterType())){
            memberConfig.setWhiteList(addOrRemoveValue(memberConfig.getWhiteList(),memberId.toString(),null));
        }else{
            memberConfig.setBlackList( addOrRemoveValue(memberConfig.getBlackList(),memberId.toString(),null));
        }

        return memberConfigManager.updateById(memberConfig);
    }

    /**
     * 获取白名单/黑名单列表
     * @param query
     * @return
     */
    @Override
    public PageInfo<MemberConfigVO> memberList(MemberListQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<MemberConfigVO> list = memberConfigManager.listMember(query);
        return PageInfo.of(list);
    }

    /**
     * 管理员获取白名单列表
     * @param query
     * @return
     */
    @Override
    public PageInfo<MemberConfigVO> getWhiteList(MemberListQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<ImMemberConfigEntity> memberConfigList = memberConfigManager.getWhiteMemberConfigList();
        return PageInfo.of(convertMemberConfigVo(memberConfigList));
    }


    // ################################## 私有方法  ##################################


    /**
     * 移除/添加 黑/白名单 成员
     * @param input
     * @param valueToRemove
     * @param valueToAdd
     * @return
     */
    private static String addOrRemoveValue(String input, String valueToRemove,String valueToAdd) {
        if(StrUtil.isBlank(input)){
            return input;
        }
        // 1. 使用 Hutool 的 StrUtil.split 方法将字符串按逗号分隔成列表
        List<String> values = StrUtil.split(input, StrUtil.COMMA);

        // 2. 使用 Stream 过滤掉不需要的值
        Set<String> filteredValues = values.stream()
                .filter(value -> !value.trim().equals(valueToRemove))
                .collect(Collectors.toSet());

        // 3. 如果需要加入新值，则添加到集合中
        if (StrUtil.isNotBlank(valueToAdd)) {
            filteredValues.add(valueToAdd.trim());
        }

        // 3. 使用 Hutool 的 StrUtil.join 方法将列表重新拼接成逗号分隔的字符串
        return StrUtil.join(StrUtil.COMMA, filteredValues);
    }

    /**
     * 转换vo类
     * @param list
     * @return
     */
    public List<MemberConfigVO> convertMemberConfigVo( List<ImMemberConfigEntity> list){
        List<MemberVO> memberList = memberService.getMemberList();
        List<Long> collect = list.stream().map(ImMemberConfigEntity::getMemberId).collect(Collectors.toList());
        List<MemberVO> memberVOList = memberList.stream().filter(item -> collect.contains(item.getId())).collect(Collectors.toList());
        return memberVOList.stream().map(item-> Convert.convert(MemberConfigVO.class,item)).collect(Collectors.toList());
    }
}
